/*
 * Copyright 2012 Marsrutai.lt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.manager;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import lt.marsrutai.mobile.android.util.PreferenceUtils;

import android.app.Activity;
import android.content.Context;

/**
 * Contains common methods for application preference handling.
 *
 * @author Martynas
 * @author Justas
 */
public class AppPreferenceManager {

    protected Activity activity;
    protected Object caller;

    public AppPreferenceManager(Activity activity, Object caller) {
        this.activity = activity;
        this.caller = caller;
    }

    /**
     * Calls findPreference(key) on the provided caller
     *
     * @param host
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
    protected <T> T findPreference(String key) {
        try {
            Method findPreference = caller.getClass().getMethod("findPreference", CharSequence.class);

            return (T) findPreference.invoke(caller, key);
        }
        catch (NoSuchMethodException e) {
        }
        catch (IllegalArgumentException e) {
        }
        catch (IllegalAccessException e) {
        }
        catch (InvocationTargetException e) {
        }

        return null;
    }
    
    /**
     * Utility method for {@link PreferenceDefaultValueResolvers#resolveDefaultValue(Context, String)}. 
     * Uses current activity as context.
     * 
     * @param key
     * @return
     */
    protected <T> T resolvePreferenceDefaultValue(String key) {
        return PreferenceDefaultValueResolvers.<T>resolveDefaultValue(activity, key);
    }
    
    /**
     * Utility method for {@link PreferenceUtils#getPreferenceValue(Context, String)}. 
     * Uses current activity as context.
     * 
     * @param key
     * @return
     */
    protected <T> T resolvePreferenceValue(String key) {
        return PreferenceUtils.<T>getPreferenceValue(activity, key);
    }

}
